$(function(){
    initWholeTree();
});


function initWholeTree() {
    var setting = {
        "view": {
            "addDiyDom": showMyIcon,
            "addHoverDom": addHoverDom,
            "removeHoverDom": removeHoverDom
        },
        "data": {
            "key": {
                "url": "notExistsProperty" // 阻止点击节点后跳转
            }
        }
    };
    $.ajax({
        "url":"/menu/get/whole/tree",
        "type":"post",
        "dataType":"json",
        "success":function(response){
            var result = response.result;
            if(result == "SUCCESS") {
                var zNodes = response.data;
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            }
            if(result == "FAILED") {
                layer.msg("加载菜单数据失败！原因是："+response.message);
            }
        },
        "error":function(response){
            layer.msg("加载菜单数据失败！原因是："+response.message);
        }
    });
}



function showMyIcon(treeId, treeNode) {
    console.log(treeId);
    console.log(treeNode);
    var currentNodeId=treeNode.tId;
    var newClass=treeNode.icon;
    var targetSpanId = currentNodeId + "_ico";
    $('#'+targetSpanId).removeClass().addClass(newClass).css("background","");
}

//鼠标悬浮
function addHoverDom(treeId, treeNode) {

    // 在执行添加前，先进行判断，如果已经添加过，就停止执行
    // 组装按钮组所在的span标签的id
    var btnGrpSpanId = treeNode.tId + "_btnGrp";

    var btnGrpSpanLength = $("#"+btnGrpSpanId).length;

    if(btnGrpSpanLength > 0) {
        return ;
    }

    //获取按钮组
    var $btnGrpSpan=generateBtnGrp(treeNode);

    // 由于按钮组是放在当前节点中的超链接（a标签）后面，所以先定位到a标签
    // 按id生成规则组装a标签的id
    var anchorId =treeNode.tId+"_a";
    // 在a标签后面追加按钮组
    $("#"+anchorId).append($btnGrpSpan);

}

//鼠标移出节点时调用此方法
function removeHoverDom(treeId, treeNode) {

    // 组装按钮组所在的span标签的id
    var btnGrpSpanId = treeNode.tId + "_btnGrp";

    // 删除对应的元素
    $("#"+btnGrpSpanId).remove();

}

//生成并返回按钮组
function generateBtnGrp(treeNode) {

    var menuId = treeNode.id;

    //定义三个按钮
    var addBtn = "<a onclick='showAddModal(this)' id='"+menuId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='添加子节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-plus rbg'></i></a>";
    var editBtn = "<a onclick='showEditModal(this)' id='"+menuId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='编辑节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-edit rbg'></i></a>";
    var removeBtn = "<a onclick='showConfirmModal(this)' id='"+menuId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='删除节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-times rbg'></i></a>";

    var btnGrpSpanId = treeNode.tId + "_btnGrp";

    // 生成span标签对应的jQuery对象
    var $span = $("<span id='"+btnGrpSpanId+"'></span>");

    //判断级别
    var level = treeNode.level;
    if(level==0){
        $span.append(addBtn);
    }
    if(level==1){
        if(treeNode.children.length>0){
            $span.append(addBtn);
            $span.append(editBtn);
        }else{
            $span.append(addBtn);
            $span.append(editBtn);
            $span.append(removeBtn);
        }
    }
    if(level == 2) {
        $span.append(editBtn+" "+removeBtn);
    }
    return $span;

}

//添加菜单
function showAddModal(currentBtn) {

    // 打开模态框
    $("#menuAddModal").modal("show");

    // 将当前节点的id存入全局变量
    window.menuId = currentBtn.id;
}


//确定添加
$("#menuAddBtn").click(function () {
    // 收集表单填写的数据
    var name = $.trim($("#menuAddModal [name='name']").val());
    var url = $.trim($("#menuAddModal [name='url']").val());
    var icon = $("#menuAddModal [name='icon']:checked").val();
    if(name == null || name == "") {
        layer.msg("请填写菜单项名称！");
        return ;
    }

    if(url == null || url == "") {
        layer.msg("请填写菜单项对应的访问地址！");
        return ;
    }
    // 发送Ajax请求
    $.ajax({
        "url":"/menu/save",
        "type":"post",
        "dataType":"json",
        "data":{
            "name":name,
            "url":url,
            "pid":window.menuId,   // 当前操作的节点是新节点的父节点
            "icon":icon
        },
        "success":function(response){

            var result = response.result;

            if(result == "SUCCESS") {
                layer.msg("操作成功！");

                initWholeTree();
            }

            if(result == "FAILED") {
                layer.msg(response.message);
            }

        },
        "error":function(response){
            layer.msg(response.message);
        }
    });

    $("#menuAddModal").modal("hide");
});

//修改
// 在点击编辑按钮时执行这个函数，打开模态框
function showEditModal(currentBtn) {

    // 打开模态框
    $("#menuEditModal").modal("show");

    // 获取当前节点的id存入全局变量
    window.menuId = currentBtn.id;

    // 发送Ajax请求
    $.ajax({
        "url":"/menu/get/"+window.menuId,
        "type":"get",
        "dataType":"json",
        "success":function(response) {

            var result = response.result;

            if(result == "SUCCESS") {

                // 从响应数据中获取Menu对象
                var menu = response.data;

                // 获取各个属性值
                var name = menu.name;

                var url = menu.url;

                var icon = menu.icon;

                // 设置各个对应的表单项
                $("#menuEditModal [name='name']").val(name);

                $("#menuEditModal [name='url']").val(url);

                // radio需要让value值和后端查询到的icon一致的设置为被选中
                $("#menuEditModal [name='icon'][value='"+icon+"']").attr("checked",true);
            }

            if(result == "FAILED") {
                layer.msg(response.message);
            }
        },
        "error":function(response) {
            layer.msg(response.message);
        }
    });
}

//确定修改
$("#menuEditBtn").click(function(){

    // 收集表单填写的数据
    var name = $.trim($("#menuEditModal [name='name']").val());
    var url = $.trim($("#menuEditModal [name='url']").val());
    var icon = $("#menuEditModal [name='icon']:checked").val();

    if(name == null || name == "") {
        layer.msg("请填写菜单项名称！");
        return ;
    }

    if(url == null || url == "") {
        layer.msg("请填写菜单项对应的访问地址！");
        return ;
    }
// 发送Ajax请求
    $.ajax({
        "url":"/menu/update",
        "type":"post",
        "dataType":"json",
        "data":{
            "id":window.menuId,
            "name":name,
            "url":url,
            "icon":icon
        },
        "success":function(response){

            var result = response.result;

            if(result == "SUCCESS") {
                layer.msg("操作成功！");

                initWholeTree();
            }

            if(result == "FAILED") {
                layer.msg(response.message);
            }

        },
        "error":function(response){
            layer.msg(response.message);
        }
    });


    $("#menuEditModal").modal("hide");
});

//显示删除模态框
function showConfirmModal(currentBtn) {
    // 打开模态框
    $("#menudeleteModal").modal("show");
    // 获取当前节点的id存入全局变量
    window.menuId = currentBtn.id;
    $.ajax({
        "url":"/menu/get/"+window.menuId,
        "type":"get",
        "dataType":"json",
        "success":function(response) {

            var result = response.result;

            if(result == "SUCCESS") {

                // 从响应数据中获取Menu对象
                var menu = response.data;

                // 获取各个属性值
                var name = menu.name;

                // 显示要删除的菜单名
                $("#menudeleteModal [name='name']").val(name);
            }
            if(result == "FAILED") {
                layer.msg(response.message);
            }
        },
        "error":function(response) {
            layer.msg(response.message);
        }
    });

}


//确定删除
$("#menudeleteBtn").click(function() {

// 发送Ajax请求
    $.ajax({
        "url": "/menu/delete",
        "type": "post",
        "dataType": "json",
        "data": {
            "id": window.menuId
        },
        "success": function (response) {

            var result = response.result;

            if (result == "SUCCESS") {
                layer.msg("操作成功！");

                initWholeTree();
            }

            if (result == "FAILED") {
                layer.msg(response.message);
            }

        },
        "error": function (response) {
            layer.msg(response.message);
        }
    });
    $("#menudeleteModal").modal("hide");
});

